//
//  SISSMessageTenantRecommendViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/1/23.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSMessageTenantRecommendViewController.h"
#import "SISSComboBoxView.h"
#import "SISSRecommandRentCell.h"
#import "SISSTenantDetailViewController.h"
#import "SISSNetworkingManager+Home.h"
#import "SISSJsonRequestNetworkingManager+Resources.h"
#import "SISSTabBarController.h"

static NSString *recommendTenantCellReuseID = @"recommendTenantCellReuseID";

@interface SISSMessageTenantRecommendViewController ()<UITableViewDelegate,UITableViewDataSource,SISSComboBoxViewDelegate,SISSRecommandRentCellDelegate>

/** 租客数组 */
@property (strong, nonatomic) NSArray<SISSTenantModel *> *tenantArr;

/** tableView */
@property (weak, nonatomic) SISSBaseTableView *tableView;
/* 下一步按钮 */
@property (weak, nonatomic) UIButton *recommendButton;

/** 可见范围 */
@property (assign, nonatomic) NSInteger visibleRange;
/** 排序规则 */
@property (assign, nonatomic) NSInteger orderAttrs;
/** 区域 */
@property (copy, nonatomic) NSString *region;
/** 街道办 */
@property (copy, nonatomic) NSString *regionDetail;
/** 价格 */
@property (copy, nonatomic) NSString *price;
/** 户型 */
@property (copy, nonatomic) NSString *houseType;
/** 面积 */
@property (copy, nonatomic) NSArray *area;
/** 朝向 */
@property (copy, nonatomic) NSArray *direction;
/** 装修程度 */
@property (copy, nonatomic) NSArray *decoration;
/** pageNo */
@property (assign, nonatomic) NSInteger pageNo;

/* lastIndexPath */
@property (strong, nonatomic) NSIndexPath *lastIndexPath;
/* isSelect */
@property (assign, nonatomic) BOOL isSelect;

@end

@implementation SISSMessageTenantRecommendViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 上下拉刷新
    __weak typeof(self) weakSelf = self;
    [[SISSRefresh sharedRefresh] prepareHeaderRefresh:self.tableView loadDataBlock:^{
        [weakSelf upDownLoadData];
    }];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 加载数据
    [self requestTenantData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.filterView.comBoBoxView dismissPopView];
}


#pragma mark - 代理
#pragma mark -- SISSComboBoxViewDelegate 筛选
- (void)comboBoxViewDidSelectDisplayTypeNormalWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title {
    
    if ([rootItemTitle isEqualToString:@"租金预算"]) {
        self.price = title;
    } else if ([rootItemTitle isEqualToString:@"意向户型"]) {
        self.houseType = title;
    }
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.pageNo = 1;
    [self requestTenantData];
    
}

- (void)comboBoxViewDidSelectDisplayTypeMultilayerWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title subtitle:(NSString *)subtitle {
    
    self.region = title;
    self.regionDetail = subtitle;
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.pageNo = 1;
    [self requestTenantData];
    
}

- (void)comboBoxViewDidSelectDisplayTypeFiltersWithTitle:(NSString *)title subtitles:(NSArray *)subtitles {
    
    if ([title isEqualToString:@"面积"]) {
        self.area = @[];
        self.area = subtitles;
    } else if ([title isEqualToString:@"朝向"]) {
        self.direction = @[];
        self.direction = subtitles;
    } else if ([title isEqualToString:@"装修程度"]) {
        self.decoration = @[];
        self.decoration = subtitles;
    }
}

- (void)comboBoxViewDisplayTypeFiltersConfirmClickAction {
    
    self.pageNo = 1;
    [self requestTenantData];
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.area = @[];
    self.direction = @[];
    self.decoration = @[];
}

#pragma mark -- UITableViewDelegate & UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    [tableView tableViewDisplayWithMessage:@"没有找到相关租客！" ifNecessaryForRowCount:self.tenantArr.count];
    if (self.tenantArr.count != 0) {
        return self.tenantArr.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SISSRecommandRentCell *cell = [tableView dequeueReusableCellWithIdentifier:recommendTenantCellReuseID forIndexPath:indexPath];
    cell.recommandDelegate = self;
    cell.isShowFullName = YES;
    cell.tenantModel = self.tenantArr[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 去除tableView的选中状态
 
    SISSTenantDetailViewController *vc = [[SISSTenantDetailViewController alloc] init];
    vc.isHiddenBottomButton = YES;
    vc.tenantModel = self.tenantArr[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - SISSRecommandRentCellDelegate
- (BOOL)recommandRentCell:(SISSRecommandRentCell *)cell checkButtonIsSelected:(BOOL)isSelected {
    
    [self.recommendButton setBackgroundColor: isSelected ? COLOR(0x349DC5) : COLOR(0x8998A5)];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    self.tenantArr[self.lastIndexPath.row].isSelected = NO;
    self.tenantArr[indexPath.row].isSelected = isSelected;
    self.isSelect = isSelected;
    self.lastIndexPath = indexPath;
    
    [self.tableView reloadData];
    return NO;
}

#pragma mark - 下一步按钮点击事件
- (void)recommendButtonClickAtion {
    
    if (!self.isSelect) return;
    SISSTenantModel *model = self.tenantArr[self.lastIndexPath.row];
    if (self.recommendBlock) {
        self.recommendBlock(model);
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

#pragma mark - 上下拉刷新加载方法
- (void)upDownLoadData {

    [self requestTenantData];
}

- (void)reloadMoreData {
    
    [self requestTenantData];
}

#pragma mark -
- (void)requestTenantData {
    
    // 非空处理
    //    NSInteger visibleRange = self.visibleRange == 2 ? self.visibleRange : 1;
    //    NSInteger orderAttrs = self.orderAttrs ? self.orderAttrs : 0;
    NSString *region = self.region ? self.region : @"不限";
    NSString *regionDetail = self.regionDetail ? self.regionDetail : @"不限";
    NSString *price = self.price ? self.price : @"";
    NSString *houseType = self.houseType ? self.houseType : @"不限";
    
    NSDictionary *parameters = @{
                                 @"spId":[SISSUserAccount shared].spId,
                                 @"region":region,
                                 @"regionDetail":regionDetail,
                                 @"price":price,
                                 @"houseType":houseType,
                                 @"area":self.area ,
                                 @"direction":self.direction,
                                 @"decoration":self.decoration
                                 };

    WeakSelf
    [kJsonRequestNetworkingManager requestEntrustTenantResourceWithParameters:parameters success:^(NSArray<SISSTenantModel *> *tenantResources) {
        
        weakSelf.tenantArr = tenantResources;
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [weakSelf.tableView reloadData];
            
            [weakSelf.tableView.mj_header endRefreshing];
        }];
        
    } failed:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        NSLog(@"%@",error);
    }];
}

#pragma mark - 设置UI
- (void)setupSubviews {
    [super setupSubviews];
    
    // 添加筛选视图
    SISSComboBoxView *filterView = [[SISSComboBoxView alloc] initWithFrame:CGRectMake(0, NAVIGATION_HEIGHT, SCREEN_WIDTH, 44) isHouseResource:NO isCooperation:NO priceTitleStr:@"租金预算"];
    filterView.delegate = self;
    
    [self.view addSubview:filterView];
    self.filterView = filterView;
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    tableView.dataSource = self;
    tableView.delegate = self;
    // 自动行高
    tableView.estimatedRowHeight = 80;
    tableView.rowHeight = UITableViewAutomaticDimension;
    [tableView registerClass:[SISSRecommandRentCell class] forCellReuseIdentifier:recommendTenantCellReuseID];
    //    [tableView registerNib:[UINib nibWithNibName:@"SISSHousingCell" bundle:nil] forCellReuseIdentifier:rentCellReuseID];
    
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    UIButton *recommendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    NSString *recommendButtonStr = @"推荐";
    [recommendButton setTitle:recommendButtonStr forState:UIControlStateNormal];
    [recommendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [recommendButton setBackgroundColor:COLOR(0x8998A5)];
    [recommendButton addTarget:self action:@selector(recommendButtonClickAtion) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:recommendButton];
    self.recommendButton = recommendButton;
    
    // 自动布局
    WeakSelf
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.top.equalTo(filterView.mas_bottom);
        make.bottom.equalTo(recommendButton.mas_top);
    }];
    
    [recommendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_equalTo(49);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(weakSelf.view);
        }
    }];
}

#pragma mark - Getter & Setter

- (NSArray *)area {
    if (_area == nil) {
        _area = [NSArray array];
    }
    return _area;
}

- (NSArray *)direction {
    if (_direction == nil) {
        _direction = [NSArray array];
    }
    return _direction;
}

- (NSArray *)decoration {
    if (_decoration == nil) {
        _decoration = [NSArray array];
    }
    return _decoration;
}


@end
